<template>
  <div class="user">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" shadow="always">
      <!-- 搜索与添加 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
            ><el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button> </el-input
        ></el-col>
        <el-col :span="10">
          <el-button type="primary" @click="showDialog = true">添加</el-button>
        </el-col>
      </el-row>
      <!--     用户列表区 -->
      <el-table :data="userList" border>
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column
          label="姓名"
          prop="username"
          width="80"
        ></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" width="90">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#778899"
              @change="stateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350">
          <template v-slot="scope">
            <!-- 编辑 -->

            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editInfo(scope.row.id)"
              >编辑</el-button
            >
            <!--  删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="isDelete(scope.row.id)"
              >删除</el-button
            >
            <!--   分配角色 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-s-custom"
                size="mini"
                @click="distrubuteRole(scope.row)"
                >分配角色</el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加用户 -->
      <el-dialog
        title="添加用户"
        :visible.sync="showDialog"
        width="50%"
        @close="closeAddDialog"
      >
        <!-- 内容主体区域 -->
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password" type="password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="ruleForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog = false">取 消</el-button>
          <el-button type="primary" @click="preadd">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户信息 -->

      <el-dialog
        title="修改用户信息"
        width="50%"
        :visible.sync="showEdit"
        @close="closeEdit"
      >
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editRef"
          label-width="100px"
        >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showEdit = false">取 消</el-button>
          <el-button type="primary" @click="putEdit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog
        title="分配角色"
        :visible.sync="showDistribuRole"
        width="50%"
        @close="closeDistribRole"
      >
        <div class="distributeRole">
          <p>当前用户名：{{ roleInfo.username }}</p>
          <p>当前用户角色：{{ roleInfo.role_name }}</p>
          <p>
            选择角色：<el-select
              v-model="selectRoleId"
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in totalRoles"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
                <!-- value中是最终保存的数据label是option显示的数据 -->
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDistribuRole = false">取 消</el-button>
          <el-button type="primary" @click="selectFinallRole">确 定</el-button>
        </span>
      </el-dialog>
      <!--   分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
        <!--  layout用于页面的显示的小功能 -->
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "",
  components: {},
  data() {
    var checkphone = (rule, value, callback) => {
      const rulephone = /^1[3456789]\d{9}$/;
      if (rulephone.test(value)) {
        callback();
      } else {
        callback(new Error("手机号格式不合法"));
      }
    };
    return {
      queryInfo: {
        query: "",
        //当前页数
        pagenum: 1,
        //当前每页显示多少条数据
        pagesize: 2,
      },
      userList: [],
      total: 0,
      showDialog: false, //添加用户对话框的显示隐藏
      showEdit: false, //修改用户对话框的显示隐藏
      //添加用户的表单数据
      ruleForm: {
        username: "admin1",
        password: "",
        email: "1265165@qq.com",
        mobile: "17854491158",
      },
      //验证手机号码的规则

      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: checkphone,
            trigger: "blur",
          },
        ],
      },
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: checkphone,
            trigger: "blur",
          },
        ],
      },
      showDistribuRole: false,
      //即将分配权限的用户信息
      roleInfo: {},
      totalRoles: [],
      selectRoleId: "",
    };
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$request({
        url: "users",
        params: this.queryInfo,
      });
      //console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error("获取用户失败");
      }
      this.total = res.data.total;
      this.userList = res.data.users;
    },
    //监听pagesize改变的事件
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    //监听页码值的改变
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    /* 监听开关状态的改变 */
    async stateChange(state) {
      console.log(state);
      const { data: res } = await this.$request({
        url: `users/${state.id}/state/${state.mg_state}`,
        method: "put",
      });
      console.log(res);
      if (res.meta.status !== 200) {
        state.mg_state = !stata.mg_state;
        this.$message.error("状态修改失败");
      } else {
        this.$message.success("状态修改成功");
      }
    },
    //监听添加用户对话框的关闭
    closeAddDialog() {
      this.$refs.ruleForm.resetFields();
    },
    //添加预验证
    preadd() {
      this.$refs.ruleForm.validate(async (val) => {
        console.log(val);
        if (!val) return;
        const { data: res } = await this.$request({
          url: "users",
          method: "post",
          data: this.ruleForm,
        });
        console.log(res);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
          this.showDialog = false;
          return;
        }
        this.$message.success("添加用户成功");
        //重新获取用户列表
        this.getUserList();
        this.showDialog = false;
      });
    },
    //根据id请求修改表单的信息
    async editInfo(id) {
      this.showEdit = true;
      const { data: res } = await this.$request({
        url: "users/" + id,
      });

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.editForm = res.data;
    },
    //表单关闭重验证
    closeEdit() {
      this.$refs.editRef.resetFields();
    },
    //确定修改并提交
    putEdit() {
      this.$refs.editRef.validate(async (val) => {
        //  console.log(val);
        if (!val) return;
        const { data: res } = await this.$request({
          url: "users/" + this.editForm.id,
          method: "put",
          data: {
            id: this.editForm.id,
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          },
        });
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败");
          this.showEdit = false;
        }
        this.showEdit = false;
        this.getUserList();
        this.$message.success("修改成功");
      });
    },
    //删除用户
    async isDelete(id) {
      this.$confirm("此操作将永久删除该用户信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then((res) => {
          console.log(res);
          this.$request({
            url: "users/" + id,
            method: "delete",
          }).then((res) => {
            console.log(res);

            if (res.data.meta.status != 200) {
              return this.$message.error("删除用户失败");
            }
            this.$message.success("删除用户成功");
            this.getUserList();
          });
        })
        .catch((err) => {
          console.log(err);
          this.$message.info("已取消删除");
        });
    },
    //分配角色
    async distrubuteRole(role) {
      this.roleInfo = role;
      //获取所有角色列表
      const { data: res } = await this.$request({
        url: "roles",
        method: "get",
      });
      if (res.meta.status !== 200) {
        return;
      }
      this.totalRoles = res.data;
      this.showDistribuRole = true;
    },
    closeDistribRole() {
      (this.selectRoleId = ""), (this.roleInfo = {});
    },

    async selectFinallRole() {
      //用户未选择角色
      if (!this.selectRoleId) {
        return this.$message.error("请选择用户角色");
      }
      const { data: res } = await this.$request({
        url: `users/${this.roleInfo.id}/role`,
        method: "put",
        data: {
          rid: this.selectRoleId,
        },
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.getUserList();
      this.$message.success(res.meta.msg);
      this.showDistribuRole = false;
    },
  },
  created() {
    this.getUserList();
  },
};
</script>
<style scoped>
.box-card {
  margin-top: 25px;
}
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 12px;
}
.distributeRole p {
  padding: 15px 0;
}
</style>
